package com.ocom.webapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.MapKey;
import com.ocom.common.entity.access.EntityDeptInfo;
import com.ocom.common.entity.card.EntityCardInfo;
import com.ocom.common.entity.card.EntityXfAccountInfo;
import com.ocom.common.entity.card.EntityXfAccountType;
import com.ocom.common.entity.human.EntityPersonTag;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.human.ManagePerTagRelationRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.*;
import com.ocom.common.vo.human.UserListVo;
import com.ocom.common.vo.human.XfUserInfoVo;
import com.ocom.common.vo.webapi.AddVo;
import com.ocom.common.vo.webapi.ExcelAddPersonVo;
import com.ocom.common.vo.webapi.UpdateAccessVo;
import com.ocom.redis.util.RedisUtil;
import com.ocom.security.utils.SecurityUtils;
import com.ocom.webapi.feign.AccessClientService;
import com.ocom.webapi.feign.HumanClientService;
import com.ocom.webapi.feign.MqSimpleService;
import com.ocom.webapi.feign.PayConfigClientService;
import com.ocom.webapi.service.AccessService;
import com.ocom.webapi.service.PersonnelPageService;
import com.ocom.webapi.vo.xfpersonnel.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static cn.hutool.poi.excel.cell.CellUtil.getCellValue;

@Slf4j
@Service
public class PersonnelPageServiceImpl implements PersonnelPageService {
    @Autowired
    private HumanClientService humanClientService;

    @Autowired
    private PayConfigClientService payConfigClientService;


    @Autowired
    private AccessService accessService;

    @Autowired
    AccessClientService accessClientService;


    @Resource
    RedisUtil redisUtil;

    @Autowired
    MqSimpleService mqSimpleService;

    // 人员列表（PersonnelPageOnShow/onShow）
    @Override
    public Result PersonnelPageOnShow(OnShowVo onShowVo) {
        Map<String, Object> map = new HashMap<>();
        MapKey mapKey = new MapKey();
        map.put(mapKey.getKey_comId(),onShowVo.getComId());
        map.put(mapKey.getKey_deptId(),onShowVo.getDeptId());
        map.put(mapKey.getKey_pCode(),onShowVo.getPCode());
        map.put(mapKey.getKey_pName(),onShowVo.getPName());
        map.put(mapKey.getKey_status(),onShowVo.getStatus());
        map.put(mapKey.getKey_page(),onShowVo.getPage());
        map.put(mapKey.getKey_size(),onShowVo.getSize());
        map.put("accountState",onShowVo.getAccountState());
        map.put("pTags",onShowVo.getPTags());
        map.put("cardNo",onShowVo.getCardNo());
        map.put("bankNo",onShowVo.getBankNo());
        if(!CommonUtil.isNull(onShowVo.getPPhone())){
            map.put("pPhone",onShowVo.getPPhone());
        }
        if(!CommonUtil.isNull(onShowVo.getPIdentity())){
            map.put("pIdentity",onShowVo.getPIdentity());
        }

        return humanClientService.GetPersonnelList(map);
    }

    // 账号信息（PersonnelPage/info）
    @Override
    public Result PersonnelPageInfo(InfoVo infoVo) {
        Result result = payConfigClientService.GetXFAccount(infoVo.getComId(),infoVo.getPId(),-1);
        if (result.getCode()!=200){
            return ResultUtil.error(result.getCode());
        }
        EntityXfAccountInfo entityXfAccountInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityXfAccountInfo.class);
        if (entityXfAccountInfo == null){
            // 返回的内容为空，判断accTypeId
            if (infoVo.getAccTypeId() == null || infoVo.getAccTypeId().equals(0)){
                Map<String, Object> map = new HashMap<>();
                map.put("code",814);
                map.put("msg","账号未初始化请选择账号类型");
                return ResultUtil.success(map);
            }
            if (infoVo.getAccTypeId() > 0){
                Map<String, Object> map = new HashMap<>();
                MapKey mapKey = new MapKey();
                map.put(mapKey.getKey_comId(),infoVo.getComId());
                map.put(mapKey.getKey_pId(),infoVo.getPId());
                map.put(mapKey.getKey_accountNo(),infoVo.getComId()+"P"+infoVo.getPId());
                map.put(mapKey.getKey_accountName(),infoVo.getComId()+"P"+infoVo.getPId());
                map.put(mapKey.getKey_accountState(),0);
                map.put(mapKey.getKey_accTypeId(),infoVo.getAccTypeId());
                payConfigClientService.AddXFAccount(map);
            }
            Result result1 = payConfigClientService.GetXFAccount(infoVo.getComId(),infoVo.getPId(),-1);
            if (result1.getCode()!=200){
                return ResultUtil.error(result1.getCode());
            }
            entityXfAccountInfo= JSON.parseObject(JSON.toJSONString(result1.getData()), EntityXfAccountInfo.class);
        }
        if(entityXfAccountInfo == null){
            return ResultUtil.error(ResultEnum.Err_806);
        }
        Map<String, Object> map = new HashMap<>();
        MapKey mapKey = new MapKey();
        map.put(mapKey.getKey_comId(),entityXfAccountInfo.getComId());
        map.put(mapKey.getKey_accountId(),entityXfAccountInfo.getId());
        map.put(mapKey.getKey_accountNo(),entityXfAccountInfo.getAccountNo());
        map.put(mapKey.getKey_accountName(),entityXfAccountInfo.getAccountName());
        map.put(mapKey.getKey_accountState(),entityXfAccountInfo.getAccountState());
        map.put(mapKey.getKey_accTypeId(),entityXfAccountInfo.getAccTypeId());
        map.put(mapKey.getKey_accountRechargeMoney(),entityXfAccountInfo.getAccountRechargeMoney());
        map.put(mapKey.getKey_accountSubsidyMoney(),entityXfAccountInfo.getAccountSubsidyMoney());
        if(entityXfAccountInfo.getEndDate()!=null){
            map.put(mapKey.getKey_endDate(),DateUtil.getStrDate2(entityXfAccountInfo.getEndDate(),"yyyy-MM-dd"));
        }else{
            map.put(mapKey.getKey_accountSubsidyMoney(),null);
        }
        Result result2 = payConfigClientService.GetXFAccountTypeDetails(infoVo.getComId(), infoVo.getAccTypeId());
        map.put(mapKey.getKey_accTypeName(),"类型异常");
        if (result2.getCode() == 200){
            log.info("消类类型 参数【{}】 获取返回【{}】",infoVo.getAccTypeId(),result2);
            EntityXfAccountType entityXfAccountType = JSON.parseObject(JSON.toJSONString(result2.getData()), EntityXfAccountType.class);
            if(entityXfAccountType!=null && entityXfAccountType.getAccTypeName()!=null){
                map.put(mapKey.getKey_accTypeName(),entityXfAccountType.getAccTypeName());
            }
        }
        String accountNo = infoVo.getComId()+"P"+infoVo.getPId();
        Result result1 = payConfigClientService.GetCardInfo(infoVo.getComId(), accountNo);
        if (result1.getCode()==200){
            EntityCardInfo entityCardInfo = JSON.parseObject(JSON.toJSONString(result1.getData()), EntityCardInfo.class);
            if (entityCardInfo!=null){
                map.put(mapKey.getKey_cardNo(),entityCardInfo.getCardNo());
                map.put(mapKey.getKey_endTime(),entityCardInfo.getEndDate());
                map.put(mapKey.getKey_cardState(),entityCardInfo.getCardState());
                map.put(mapKey.getKey_useTimeNow(),entityCardInfo.getUseTimeNow());
                map.put(mapKey.getKey_useLsNow(),entityCardInfo.getUseLsNow());
            }

        }
        return ResultUtil.success(map);
    }

    // 查询人员未脱敏的信息（PersonnelPage/NoDesensitized）
    @Override
    public Result PersonnelPageNoDesensitized(Long comId, Long pId) {

        return humanClientService.GetPersonInfo(comId,pId);
    }

    // 新增人员信息（PersonnelPage/add）
    @Override
    public Result PersonnelPageAdd(AddVo addVo) {
        Map<String, Object> map = new HashMap<>();
        MapKey mapKey = new MapKey();
        map.put(mapKey.getKey_comId(), SecurityUtils.getYoCiUser().getComId());
        map.put(mapKey.getKey_deptId(),addVo.getDeptId());
        map.put(mapKey.getKey_pCode(),StringUtils.trim(addVo.getPCode()," "));
        String pwd = StringUtils.trim(addVo.getPPwd()," ");
        map.put(mapKey.getKey_pPwd(),CommonUtil.isNull(pwd)?"000000":pwd);
        map.put(mapKey.getKey_pName(),StringUtils.trim(addVo.getPName()," "));
        map.put(mapKey.getKey_pSex(),addVo.getPSex());
        map.put(mapKey.getKey_pType(),addVo.getPType());
        map.put(mapKey.getKey_pPhone(),StringUtils.trim(addVo.getPPhone()," "));
        map.put(mapKey.getKey_pIdentity(),StringUtils.trim(addVo.getPIdentity()," "));
        map.put(mapKey.getKey_pBorn(),addVo.getPBorn());
        map.put(mapKey.getKey_pAddress(),addVo.getPAddress());
        map.put(mapKey.getKey_pPhotoUrl(),StringUtils.trim(addVo.getPPhotoUrl()," "));
        map.put(mapKey.getKey_status(),addVo.getStatus());
        map.put("bankNo",addVo.getBankNo());



//        map.put("pTags",addVo.getPTags());

        if(!CommonUtil.isNull(addVo.getPIdentity())){
            if (!IdentificationCodeUtil.isIdentityCode(addVo.getPIdentity())
            &&  !IdentificationCodeUtil.isPassportCode(addVo.getPIdentity())){
                return ResultUtil.error(ResultEnum.Err_2021);
            }
        }
        Result result = humanClientService.AddPerson(map);
        //添加人员返回
        log.info("result",result);
        if (result.getCode()!=200){
            return ResultUtil.error(result.getCode());
        }
        EntityPersonnelInfo personnelInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityPersonnelInfo.class);
        assert personnelInfo != null;
        Map<String, Object> map1 = new HashMap<>();
        map1.put(mapKey.getKey_comId(),addVo.getComId());
        map1.put(mapKey.getKey_pId(),personnelInfo.getPId());
        map1.put(mapKey.getKey_accountNo(),addVo.getAccountNo());
        map1.put(mapKey.getKey_accTypeName(),addVo.getAccountName());
        map1.put(mapKey.getKey_accountState(),0);
        map1.put(mapKey.getKey_accTypeId(),addVo.getAccTypeId());
        map1.put("accountNo",addVo.getComId()+"P"+personnelInfo.getPId());
        map1.put("accountName",map1.get("accountNo"));
        map1.put(mapKey.getKey_endDate(),DateUtil.getStrDate2(addVo.getEndDate(),"yyyy-MM-dd"));
        Result result1 = payConfigClientService.AddXFAccount(map1);
//        System.out.println(result1);

        setPersonTag(0, personnelInfo.getComId(), personnelInfo.getPId(), addVo.getPTags());

        return ResultUtil.success();
    }

    private void setPersonTag(Integer type, Long comId, Long pId, List<UserListVo.PTags> pTags){
        try {
            ManagePerTagRelationRequest request = new ManagePerTagRelationRequest();
            List<ManagePerTagRelationRequest.PerList> perLists = request.getPerLists();
            ManagePerTagRelationRequest.PerList perList = request.getPerList();
            perList.setPId(pId);
            request.setType(type);
            request.setComId(comId);
            if (2 == type) {
                perLists.add(perList);
                request.setPerLists(perLists);
                humanClientService.managePerTagRelation(request);
            } else if (null != pTags) {
                for (UserListVo.PTags pTag : pTags) {
                    ManagePerTagRelationRequest.PerTag perTag = new ManagePerTagRelationRequest.PerTag();
                    perTag.setTagId(pTag.getTagId());
                    perList.getPerTags().add(perTag);
                }
                perLists.add(perList);
                request.setPerLists(perLists);
                humanClientService.managePerTagRelation(request);
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("设置用户标签失败！【{}】，【{}】,【{}】", pId, pTags, e.getMessage());
        }

    }

    // 修改人员信息（PersonnelPage/modify）
    @Override
    public Result PersonnelPageModify(ModifyVo modifyVo) {
        if(!SecurityUtils.getYoCiUser().getComId().equals(modifyVo.getComId())){
            return ResultUtil.error(ResultEnum.Err_4100);
        }
        Map<String, Object> map = new HashMap<>();
        MapKey mapKey = new MapKey();
        map.put(mapKey.getKey_comId(),SecurityUtils.getYoCiUser().getComId());
        map.put(mapKey.getKey_deptId(),modifyVo.getDeptId());
        map.put(mapKey.getKey_pId(),modifyVo.getPId());
        map.put(mapKey.getKey_pCode(),StringUtils.trim(modifyVo.getPCode()," "));
        map.put(mapKey.getKey_pPwd(),StringUtils.trim(modifyVo.getPPwd()," "));
        map.put(mapKey.getKey_pName(),StringUtils.trim(modifyVo.getPName()," "));
        map.put(mapKey.getKey_pSex(),modifyVo.getPSex());
        map.put(mapKey.getKey_pType(),modifyVo.getPType());
        map.put(mapKey.getKey_pPhone(),StringUtils.trim(modifyVo.getPPhone()," "));
        map.put(mapKey.getKey_pIdentity(),StringUtils.trim(modifyVo.getPIdentity()," "));
        map.put(mapKey.getKey_pBorn(),modifyVo.getPBorn());
        map.put(mapKey.getKey_pAddress(),modifyVo.getPAddress());
        map.put(mapKey.getKey_pPhotoUrl(),StringUtils.trim(modifyVo.getPPhotoUrl()," "));
        map.put(mapKey.getKey_status(),modifyVo.getStatus());
        map.put("bankNo",StringUtils.trim(modifyVo.getBankNo()," "));

//        map.put("pTags",modifyVo.getPTags());

        if (!CommonUtil.isNull(modifyVo.getPIdentity()) &&  !IdentificationCodeUtil.isIdentityCode(modifyVo.getPIdentity())
        &&  !IdentificationCodeUtil.isPassportCode(modifyVo.getPIdentity() )
        ){
            return ResultUtil.error(ResultEnum.Err_2021);
        }
        humanClientService.UpdatePerson(map);

        long state = 0l ;
        if(modifyVo.getEndDate()!=null){
            if(modifyVo.getEndDate().before(new Date())){
                state = 1l ;
            }
        }

        Map<String, Object> map1 = new HashMap<>();
        map1.put(mapKey.getKey_comId(),SecurityUtils.getYoCiUser().getComId());
        map1.put("pId",modifyVo.getPId());
//        map1.put(mapKey.getKey_accountId(),modifyVo.getAccountId());
        map1.put("id",modifyVo.getAccountId());
        map1.put(mapKey.getKey_accTypeId(),modifyVo.getAccTypeId());
        map1.put(mapKey.getKey_endDate(),DateUtil.getStrDate2(modifyVo.getEndDate(),"yyyy-MM-dd"));
        map1.put("accountState",state);
        payConfigClientService.UpdateXFAccount(map1);

        //重置人員白名單
        UpdateAccessVo updateAccessVo=new UpdateAccessVo();
        updateAccessVo.setComId(SecurityUtils.getYoCiUser().getComId());
        updateAccessVo.setType(5);
        updateAccessVo.setPId(modifyVo.getPId());
        accessService.updateUserAccess(updateAccessVo);

//        payConfigClientService.setXFWhiteInfo(modifyVo.getComId(),modifyVo.getPId(),state);

        setPersonTag(1, modifyVo.getComId(), modifyVo.getPId(), modifyVo.getPTags());
        return ResultUtil.success();
    }

    // 删除人员信息（PersonnelPage/delete）
    @Override
    public Result PersonnelPageDelete(DeleteVo deleteVo) {
        Long companyId = SecurityUtils.getYoCiUser().getComId();
        Long userId = deleteVo.getPId();

        //判断卡状态
        Result result4 =  payConfigClientService.GetCardInfoByPid(companyId,userId);
        if(result4.getData()!=null){
            EntityCardInfo entityCardInfo = JSON.parseObject(JSON.toJSONString(result4.getData()), EntityCardInfo.class);
            if(entityCardInfo.getCardState() == 1){
                return ResultUtil.error(ResultEnum.Err_2037);
            }
        }

        Result result23 = humanClientService.getXfUserInfo(companyId, userId);
        if (result23.getCode() == 200) {
            XfUserInfoVo xfUserInfoVo = JSONObject.parseObject(JSON.toJSONString(result23.getData()), XfUserInfoVo.class);
            if(xfUserInfoVo.getChargeBalance()!=0){
                return ResultUtil.error(ResultEnum.Err_2040);
            }
        }

        Result result = humanClientService.removePerson(companyId,0L,userId);
        if(result.getCode()!=200){
            return ResultUtil.error(result.getCode());
        }
        //移除白名单
        accessClientService.clearAccessByUser(companyId,userId,userId);
        Map<String, Object> map = new HashMap<>();
        MapKey mapKey = new MapKey();
        map.put(mapKey.getKey_comId(),companyId);
        map.put("pId",userId);
        map.put(mapKey.getKey_id(),deleteVo.getAccountId());
        map.put(mapKey.getKey_accountState(),1);
        payConfigClientService.UpdateXFAccount(map);
        payConfigClientService.setXFWhiteInfo(companyId,userId,1l);

        setPersonTag(2, deleteVo.getComId(), deleteVo.getPId(), null);

        return ResultUtil.success();
    }

    @Override
    public Result PersonnelPageBatchRemove(BatchRemoveRequest request) {
        Long companyId = request.getComId();

        for (Long pId : request.getPerList()) {
            try {
                //判断卡状态
                Result result4 =  payConfigClientService.GetCardInfoByPid(companyId,pId);
                if(result4.getData()!=null){
                    EntityCardInfo entityCardInfo = JSON.parseObject(JSON.toJSONString(result4.getData()), EntityCardInfo.class);
                    if(entityCardInfo.getCardState() == 1 || entityCardInfo.getCardState() == 0){
                        Map<String,Object> map =new HashMap<>();
                        map.put("accountNo", entityCardInfo.getAccountNo());
                        map.put("cardNo", entityCardInfo.getCardNo());
                        map.put("comId", entityCardInfo.getComId());
                        map.put("pId", entityCardInfo.getPId());
                        map.put("user", SecurityUtils.getUsername());
                        map.put("cardState", 2);
                        payConfigClientService.UpdatecardState(map);
                    }
                }

                Result result23 = humanClientService.getXfUserInfo(companyId, pId);
                XfUserInfoVo xfUserInfoVo = null;
                if (result23.getCode() == 200) {
                    xfUserInfoVo = JSONObject.parseObject(JSON.toJSONString(result23.getData()), XfUserInfoVo.class);
                    Map<String,Object> mapCharge=new HashMap<>();
                    mapCharge.put("comId",companyId);
                    mapCharge.put("pId",pId);
                    mapCharge.put("userId",SecurityUtils.getYoCiUser().getId());
                    mapCharge.put("userName",SecurityUtils.getUsername());

                    if(xfUserInfoVo.getChargeBalance() != 0){
                        mapCharge.put("rechargeMoney", -xfUserInfoVo.getChargeBalance());
                        Result result = payConfigClientService.UpdateListRecharge(mapCharge);
                        if (200 != result.getCode()){
                            log.info("批量办理人员离职-修改充值金额失败，PID：【{}】 ,message:【{}】",pId, result.getMsg());
                        }
                    }
                    if (xfUserInfoVo.getAccountSubsidyMoney() != 0) {
                        mapCharge.put("rechargeMoney", -xfUserInfoVo.getAccountSubsidyMoney());
                        Result result = payConfigClientService.updateSubsidy(mapCharge);
                        if (200 != result.getCode()){
                            log.info("批量办理人员离职-修改补贴金额失败，PID：【{}】 ,message:【{}】",pId, result.getMsg());
                        }
                    }
                }

                Result result = humanClientService.removePerson(companyId, 0L, pId);

                //移除白名单
                Result result1 = accessClientService.clearAccessByUser(companyId, pId, pId);
                if (null != xfUserInfoVo && null != xfUserInfoVo.getAccountId()) {
                    Map<String, Object> map = new HashMap<>();
                    MapKey mapKey = new MapKey();
                    map.put(mapKey.getKey_comId(),companyId);
                    map.put("pId",pId);
                    map.put(mapKey.getKey_id(),xfUserInfoVo.getAccountId());
                    map.put(mapKey.getKey_accountState(),1);
                    Result result2 = payConfigClientService.UpdateXFAccount(map);
                }

                Result result3 = payConfigClientService.setXFWhiteInfo(companyId, pId, 1l);

                setPersonTag(2, companyId, pId, null);
            }catch (Exception e) {
                e.printStackTrace();
                log.info("批量办理人员离职-失败，PID：【{}】 ,message:【{}】",pId, e.getMessage());
            }
        }

        return ResultUtil.success();
    }

    /**
     * 导入人员信息（PersonnelPage/import）
     * */
    @Override
    public Result PersonnelPageImport(Long comId, Long accTypeId,Integer importType, MultipartFile file) {

        //        1、用HSSFWorkbook打开或者创建“Excel文件对象”
        //        2、用HSSFWorkbook对象返回或者创建Sheet对象
        //        3、用Sheet对象返回行对象，用行对象得到Cell对象
        //        4、对Cell对象读写。
        //获得文件名
        Workbook workbook = null ;
        String fileName = file.getOriginalFilename();
        if(fileName.endsWith("xls")){
            //2003
            try {
                workbook = new HSSFWorkbook(file.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if(fileName.endsWith("xlsx")){
            //2007
            try {
                workbook = new XSSFWorkbook(file.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                throw new Exception("文件不是Excel文件");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        Sheet sheet = workbook.getSheetAt(0);
        int rows = sheet.getLastRowNum();// 指的行数，一共有多少行+
        if(rows==0){
            try {
                throw new Exception("请填写数据");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        List<EntityDeptInfo> list= new ArrayList<>();
        //获取完整部门树
        Result result2 = humanClientService.getDeptList(comId, 0L,1);

        if(result2.getCode()!=200){
            return ResultUtil.error(ResultEnum.Err_302);
        }

        list = JSON.parseArray(JSON.toJSONString(result2.getData()), EntityDeptInfo.class);

        //账户类型列表
        Result GetXFAccountTypeResult = payConfigClientService.GetXFAccountType(comId);
        if (200 != GetXFAccountTypeResult.getCode()) {
            return ResultUtil.error(ResultEnum.Err_302);
        }
        List<EntityXfAccountType> xfAccountTypes = JSON.parseArray(JSON.toJSONString(GetXFAccountTypeResult.getData()), EntityXfAccountType.class);
        HashMap<Integer, EntityXfAccountType> xfAccountTypeHashMap = xfAccountTypes.stream().collect(Collectors.toMap(e -> e.getAccTypeId(), e -> e, (e, e1) -> {
            return e1;
        }, HashMap::new));
        //标签列表
        Result perTagResult = humanClientService.getPerTag(comId, 1, 0);
        if (200 != perTagResult.getCode()) {
            return ResultUtil.error(ResultEnum.Err_302);
        }
        List<EntityPersonTag> entityPersonTags = JSON.parseArray(JSON.toJSONString(perTagResult.getData()), EntityPersonTag.class);
        HashMap<String, EntityPersonTag> tagHashMap = entityPersonTags.stream().collect(Collectors.toMap(e -> e.getTagName(), e -> e, (e, e1) -> {
            return e1;
        }, HashMap::new));

        Long timestamp = System.currentTimeMillis();
        Map<String,Object> map1=new HashMap<>();
        map1.put("key","ImportErr:detail:"+comId+":"+timestamp);
        map1.put("type",3);
        map1.put("name","人员批量导入");
        map1.put("timestamp",timestamp);
        map1.put("datetime", DateUtil.getDateTime());
        redisUtil.leftPush("ImportErr:"+comId,map1,86400l);


//        List<EntityPersonnelInfo> entityPersonnelInfos = new ArrayList<>();
        List<Map> errList = new ArrayList<>();

        int errCount = 0;
        boolean hadCover = false;
        List<String> codes = new ArrayList<>();

        BREAKOFF:
        for (int i = 1; i < rows+1; i++) {
            if(i>5005){
                break BREAKOFF;
            }
            MapKey mapKey = new MapKey();
            EntityPersonnelInfo entityPersonnelInfo = new EntityPersonnelInfo();
            Map<String, Object> map = new HashMap<>();
            entityPersonnelInfo.setComId(SecurityUtils.getYoCiUser().getComId());
            // 读取左端单元格
            Row row = sheet.getRow(i);
            // 行不为空
            if (row != null) {

                // **读取cell**
                //姓名
                String pName = JSON.toJSONString(getCellValue(row.getCell(0))).replace("\"", "").replace("\\t", "");
                if (StringUtils.isNotEmpty(pName) && !pName.equals("null")){
                    entityPersonnelInfo.setPName(StringUtils.trim(pName," "));
                }

                // 性别(男/女)
                String pSex = JSON.toJSONString(getCellValue(row.getCell(1))).replace("\"", "").replace("\\t", "");
                if (pSex.equals("男")) {
                    entityPersonnelInfo.setPSex(0);
                } else if (pSex.equals("女")) {
                    entityPersonnelInfo.setPSex(1);
                }

                // 人员编号
                String pCode = JSON.toJSONString(getCellValue(row.getCell(2))).replace("\"", "").replace("\\t", "");
                if (StringUtils.isNotEmpty(pCode) && !pCode.equals("null")){
                    entityPersonnelInfo.setPCode(StringUtils.trim(pCode," "));
                    errCount = 0;
                }else{
                    errCount++;
                    if(errCount>10){
                        break BREAKOFF;
                    }
                    continue ;
                }


                // 人员编号
                Long grade = 0L;
                String deptName = JSON.toJSONString(getCellValue(row.getCell(3))).replace("\"", "").replace("\\t", "");
                deptName = StringUtils.trim(deptName," ");
                String[] deptNameSplit = deptName.split("/");


                entityPersonnelInfo.setDeptId(0l);

                if(deptNameSplit.length<=0){
                    continue;
                }else {
                    Long realDeptId = 0l;
                    Boolean  flag = false;
                    for (int j=0;j<deptNameSplit.length;j++) {
                        String ndeptName = deptNameSplit[j];
                        //单位名称不作判断
                        if(!flag){
                            flag=true;
                            continue;
                        }
                        ndeptName= StringUtils.trimStart(ndeptName," ");
                        ndeptName= StringUtils.trimEnd(ndeptName," ");
                        Boolean exist = false;
                        for (EntityDeptInfo entityDeptInfo : list) {
                            //匹配到名称
                            String ndeptName1= entityDeptInfo.getDeptName();
                            ndeptName1= StringUtils.trimStart(ndeptName1," ");
                            ndeptName1= StringUtils.trimEnd(ndeptName1," ");
                            if (ndeptName1.equals(ndeptName) &&
                                    entityDeptInfo.getParentDeptId().equals(realDeptId)
                            ) {
                                exist = true;
                                realDeptId = entityDeptInfo.getDeptId();

                                if( j+1 == deptNameSplit.length){
                                    entityPersonnelInfo.setDeptId(realDeptId);
                                }
                                break;
                            }
                        }
                        if (!exist) {
                            break;
                        }
                    }
                }

//                for (int i1 = 0; i1 < deptNameSplit.length; i1++) {
//                    deptName = deptNameSplit[i1];
//                    grade++;
//                }
//                Long deptID = null;
//                Result result = humanClientService.GetDeptInfo(comId, deptID, deptName);
//                if (result.getCode() == 200) {
//                    List<EntityDeptInfo> entityDeptInfos = JSON.parseArray(JSON.toJSONString(result.getData()), EntityDeptInfo.class);
//                    if (entityDeptInfos.size() == 0) {
//                        entityPersonnelInfo.setDeptId(0L);
//                    }
//                    for (EntityDeptInfo entityDeptInfo : entityDeptInfos) {
//                        if (entityDeptInfo.getDeptName().equals(deptName)  || entityDeptInfo.getGrade().equals(grade)) {
//                            entityPersonnelInfo.setDeptId(entityDeptInfo.getDeptId());
//                        }
//                    }
//                }


                //人员密码
                String pPwd= JSON.toJSONString(getCellValue(row.getCell(4))).replace("\"", "").replace("\\t", "");
                if (StringUtils.isNotEmpty(pPwd) && !pPwd.equals("null")){
                    entityPersonnelInfo.setPPwd(StringUtils.trim(pPwd," "));
                }

                // 联系电话
                String pPhone = JSON.toJSONString(getCellValue(row.getCell(5))).replace("\"", "").replace("\\t", "");
                if (StringUtils.isNotEmpty(pPhone) && !pPhone.equals("null")){
                    entityPersonnelInfo.setPPhone(StringUtils.trim(pPhone," "));
                }

                // 身份证号码
                String pIdentity = JSON.toJSONString(getCellValue(row.getCell(6))).replace("\"", "").replace("\\t", "");
                if ( pName.isEmpty() || pName.equals("null") || deptName.isEmpty()) {
                    map.put(mapKey.getKey_pName(),pName);
                    map.put(mapKey.getKey_deptName(),deptName);
                    map.put(mapKey.getKey_pIdentity(), pIdentity);
                    errList.add(map);
                }else {
                    if (!IdentificationCodeUtil.isIdentityCode(pIdentity)
                    && !IdentificationCodeUtil.isPassportCode(pIdentity)){
                        map.put(mapKey.getKey_pName(),pName);
                        map.put(mapKey.getKey_deptName(),deptName);
                        map.put(mapKey.getKey_pIdentity(), pIdentity);
                        errList.add(map);
                    }else{
                        entityPersonnelInfo.setPIdentity(StringUtils.trim(pIdentity," "));
                    }
                }

                //银行卡号
                String bankNo = JSON.toJSONString(getCellValue(row.getCell(7))).replace("\"", "").replace("\\t", "");
                if (StringUtils.isNotEmpty(bankNo) && !bankNo.equals("null")){

                  entityPersonnelInfo.setBankNo(bankNo);
                }

                // 住址
                String pAddress = JSON.toJSONString(getCellValue(row.getCell(8))).replace("\"", "").replace("\\t", "");
                if (StringUtils.isNotEmpty(pAddress) && !pAddress.equals("null")){
                    entityPersonnelInfo.setPAddress(pAddress);
                }
                //人员图片地址
                String pPhotoUrl = JSON.toJSONString(getCellValue(row.getCell(9))).replace("\"", "").replace("\\t", "");
                if (StringUtils.isNotEmpty(pPhotoUrl) && !pPhotoUrl.equals("null")){
                    entityPersonnelInfo.setPPhotoUrl(StringUtils.trim(pPhotoUrl," "));
                }

//                //账户类型
//                String excelAccTypeId = JSON.toJSONString(getCellValue(row.getCell(10))).replace("\"", "").replace(
//                    "\\t", "");
//                if (StringUtils.isNotEmpty(excelAccTypeId) && !excelAccTypeId.equals("null")){
//                    EntityXfAccountType xfAccountType = xfAccountTypeHashMap.get(Integer.valueOf(StringUtils.trim(excelAccTypeId, " ")));
//                    if (null != xfAccountType) {
//                        entityPersonnelInfo.setAccTypeId(xfAccountType.getAccTypeId());
//                    }else {
//                        entityPersonnelInfo.setAccTypeId(accTypeId.intValue());
//                    }
//                }

                entityPersonnelInfo.setAccTypeId(accTypeId.intValue());

                //多个标签用|分隔
                String excelPerTag = JSON.toJSONString(getCellValue(row.getCell(11))).replace("\"", "").replace("\\t",
                    "");
                if (StringUtils.isNotEmpty(excelPerTag) && !excelPerTag.equals("null")){
                    List<EntityPersonTag> tags = new ArrayList<>();
                    String[] split = StringUtils.trim(excelPerTag, " ").split("\\|");
                    for (String tag : split) {
                        EntityPersonTag entityPersonTag = tagHashMap.get(tag);
                        if (null != entityPersonTag) {
                            tags.add(entityPersonTag);
                        }
                    }
                    entityPersonnelInfo.setPerTags(tags);
                }

                //账户有效期；读出来的是13位的时间戳
                String accountEndDateStr = JSON.toJSONString(getCellValue(row.getCell(12))).replace("\"", "").replace("\\t", "");
                if (!CommonUtil.isNull(accountEndDateStr)  && accountEndDateStr.length() == 10){
                    try {
                        Date accountEndDate = DateUtils.strToDate2(accountEndDateStr);
                        entityPersonnelInfo.setAccountEndDate(accountEndDate);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            if(CommonUtil.isNull(entityPersonnelInfo.getPAddress())){
                entityPersonnelInfo.setPAddress(null);
            }

            if(CommonUtil.isNull(entityPersonnelInfo.getPPhotoUrl())){
                entityPersonnelInfo.setPPhotoUrl(null);
            }

            List<EntityPersonnelInfo> entityPersonnelInfos = new ArrayList<>();
            entityPersonnelInfos.add(entityPersonnelInfo);

            log.info("excel人员信息: 【{}】", entityPersonnelInfo);

            if(CommonUtil.isNull(entityPersonnelInfo.getPCode())
            && CommonUtil.isNull(entityPersonnelInfo.getPName())){
                //姓名编号全空不传入
                continue;

            }else{
                ExcelAddPersonVo excelAddPersonVo =new ExcelAddPersonVo();
                excelAddPersonVo.setComId(comId);
                excelAddPersonVo.setAccTypeId(accTypeId);
                excelAddPersonVo.setPersonnelInfos(entityPersonnelInfos);
                excelAddPersonVo.setTimestamp(timestamp);
                excelAddPersonVo.setImportType(importType);
                mqSimpleService.ImportPerson(excelAddPersonVo);

            }

        }
//        if(hadCover){
//            return ResultUtil.success(String.format("人员编号【%s】已经存在，是否覆盖导入？",String.join(",",codes)));
//        }
//        log.info("消费人员导入插入comId{{}},accTypeId{{}},entityPersonnelInfos{{}}",comId, accTypeId,entityPersonnelInfos);

        return ResultUtil.success(errList);
    }


}
